package org.gitos.cloud.comet.logic;

/**
 * Created by shizhengchu on 16/3/18.
 */
public class ContextLogicHandler implements LogicHandler {

    private ContextLogicHandler next;
    private ContextLogicHandler pre;

    private LogicHandler handler;

    public boolean tcpbound = true;
    public boolean mqbound = true;

    private ContextPipline pipline;

    public ContextLogicHandler(LogicHandler handler, ContextPipline pipline) {
        this.handler = handler;
        this.pipline = pipline;
        if (handler != null){
            this.tcpbound = handler.tcpbound();
            this.mqbound = handler.mqbound();
        }

    }


    private ContextLogicHandler preTcpCtx(ContextLogicHandler ctx) {
        ContextLogicHandler preCtx = ctx;
        while (preCtx.pre != null) {
            preCtx = preCtx.pre;
            if (preCtx.tcpbound == true) {
                return preCtx;
            }
        }
        return null;
    }

    private ContextLogicHandler nextMQCtx(ContextLogicHandler ctx) {
        ContextLogicHandler nextCtx = ctx;
        while (nextCtx.next != null) {
            nextCtx = nextCtx.next;
            if (nextCtx.mqbound == true) {
                return nextCtx;
            }
        }
        return null;
    }

    @Override
    public boolean tcpbound() {
        return tcpbound;
    }

    @Override
    public boolean mqbound() {
        return mqbound;
    }

    public void fireTcplogic() {
        ContextLogicHandler nextCtx = preTcpCtx(this);

        if (nextCtx == null) {
            return;
        }
        nextCtx.tcplogic(nextCtx);
    }

    public void fireMqlogic() {
        ContextLogicHandler nextCtx = nextMQCtx(this);

        if (nextCtx == null) {
            return;
        }
        nextCtx.mqlogic(nextCtx);
    }


    @Override
    public void tcplogic(ContextLogicHandler ctx) {
        ctx.getHandler().tcplogic(ctx);
    }

    @Override
    public void mqlogic(ContextLogicHandler ctx) {
        ctx.getHandler().mqlogic(ctx);
    }

    public LogicHandler getHandler() {
        return handler;
    }

    public void setHandler(LogicHandler handler) {
        this.handler = handler;
    }

    public ContextLogicHandler getNext() {
        return next;
    }

    public ContextLogicHandler getPre() {
        return pre;
    }

    public void setPre(ContextLogicHandler pre) {
        this.pre = pre;
    }

    public void setNext(ContextLogicHandler next) {
        this.next = next;
    }

    public ContextPipline getPipline() {
        return pipline;
    }

    public void setPipline(ContextPipline pipline) {
        this.pipline = pipline;
    }
}
